﻿using GenerateSeeds;
using System.Text;

var connectionString =
    "Server=localhost; port=3306; Database=hzy_admin_mysql_20230227; uid=root; pwd=123456; Convert Zero Datetime=False";

//EnableLegacyTimestampBehavior 启动旧行为，避免时区问题，存储时间报错
AppContext.SetSwitch("Npgsql.EnableLegacyTimestampBehavior", true);

IFreeSql fsql = new FreeSql.FreeSqlBuilder()
    .UseConnectionString(FreeSql.DataType.MySql, connectionString)
    .UseAutoSyncStructure(false) //自动同步实体结构到数据库
    .Build(); //请务必定义成 Singleton 单例模式

var tables = fsql.DbFirst.GetTablesByDatabase();

var useStringBuilder = new StringBuilder();
foreach (var table in tables)
{
    try
    {
        if (table.Name.ToLower().Contains("_log".ToLower())) continue;

        if (table.Name.ToLower().StartsWith("__".ToLower())) continue;

        var list = fsql.Ado.Query<Dictionary<string, object>>($"select * from {table.Name} limit 500");

        if (list.Count == 0) continue;

        var sb = new StringBuilder();

        var entityName = Util.LineToHump(table.Name);

        var className = $"Migrations{entityName}ModelBuilderExtensions";

        // MigrationsLowCodeTableInfoModelBuilderExtensions.Seed(modelBuilder);
        useStringBuilder.Append(className + ".Seed(modelBuilder);");

        sb.Append($@"
namespace HZY.Repository.EntityFramework.Admin.Migrations.SeedsDatas.Datas;

  public static class {className}
    {{
        public static void Seed(this ModelBuilder modelBuilder)
        {{
// ===============================================表：{table.Name} 种子数据=============================================
modelBuilder.Entity<{entityName}>().HasData(");

        var codes = new List<string>();
        foreach (var item in list)
        {
            var rows = $"new {entityName}(){{";

            var fileds = new List<string>();
            foreach (var column in table.Columns)
            {
                var columnName = Util.LineToHump(column.Name);
                var value = item[column.Name] ?? null;

                if (value is null)
                {
                    continue;
                }

                if (value is string vStr)
                {
                    if (!string.IsNullOrWhiteSpace(vStr))
                    {
                        vStr = vStr.Trim();
                    }

                    if (vStr != null && vStr.ToString().Count(w => w == '"') > 1)
                    {
                        var start = "\"";
                        var end = "\\\"";
                        var newValue = vStr.ToString().Replace(start, end);
                        fileds.Add($"{columnName}=\"{newValue}\"");
                    }
                    else
                    {
                        fileds.Add($"{columnName}=\"{(vStr == null ? null : vStr)}\"");
                    }
                }
                else if (value is Guid && Guid.TryParse(value?.ToString(), out var v))
                {
                    fileds.Add($"{columnName}=Guid.Parse(\"{v}\")");
                }
                else if (value is DateTime || value is DateTime?)
                {
                    fileds.Add($"{columnName}=DateTime.Parse(\"{value}\")");
                }
                else if (value is bool)
                {
                    fileds.Add($"{columnName}=bool.Parse(\"{value}\")");
                }
                else if (columnName == "Phone")
                {
                }
                else if (columnName == "Id" && value is int)
                {
                }
                else if (columnName == "PermissionType" && table.Name == "sys_data_authority")
                {
                    fileds.Add($"{columnName}=SysDataAuthorityPermissionTypeEnum.Self");
                }
                else if (columnName == "Type" && table.Name == "sys_menu")
                {
                    //SysMenuTypeEnum.菜单
                    if (value is int || value is int?)
                    {
                        if ((int)value == (int)SysMenuTypeEnum.菜单)
                        {
                            fileds.Add($"{columnName}=SysMenuTypeEnum.菜单");
                        }
                        else
                        {
                            fileds.Add($"{columnName}=SysMenuTypeEnum.目录");
                        }
                    }
                }
                else if (columnName == "Mode" && table.Name == "sys_menu")
                {
                    if (value is int || value is int?)
                    {
                        if ((int)value == (int)SysMenuModeEnum.普通)
                        {
                            fileds.Add($"{columnName}=SysMenuModeEnum.普通");
                        }
                        else
                        {
                            fileds.Add($"{columnName}=SysMenuModeEnum.微前端");
                        }
                    }
                }
                else if (columnName == "State" && (table.Name == "sys_post" || table.Name == "sys_organization"))
                {
                    fileds.Add($"{columnName}=StateEnum.正常");
                }
                else if (columnName == "State" && table.Name == "quartz_job_task")
                {
                    if (value is int || value is int?)
                    {
                        if ((int)value == (int)QuartzJobTaskStateEnum.运行中)
                        {
                            fileds.Add($"{columnName}=QuartzJobTaskStateEnum.运行中");
                        }
                        else
                        {
                            fileds.Add($"{columnName}=QuartzJobTaskStateEnum.未运行");
                        }
                    }
                }
                else if (columnName == "Type" && table.Name == "quartz_job_task")
                {
                    if (value is int || value is int?)
                    {
                        if ((int)value == (int)QuartzJobTaskTypeEnum.Local)
                        {
                            fileds.Add($"{columnName}=QuartzJobTaskTypeEnum.Local");
                        }
                        else
                        {
                            fileds.Add($"{columnName}=QuartzJobTaskTypeEnum.WebApi");
                        }
                    }
                }
                else if (columnName == "RequsetMode" && table.Name == "quartz_job_task")
                {
                    if (value is int || value is int?)
                    {
                        if ((int)value == (int)QuartzJobTaskRequsetModeEnum.Delete)
                        {
                            fileds.Add($"{columnName}=QuartzJobTaskRequsetModeEnum.Delete");
                        }

                        if ((int)value == (int)QuartzJobTaskRequsetModeEnum.Get)
                        {
                            fileds.Add($"{columnName}=QuartzJobTaskRequsetModeEnum.Get");
                        }

                        if ((int)value == (int)QuartzJobTaskRequsetModeEnum.Post)
                        {
                            fileds.Add($"{columnName}=QuartzJobTaskRequsetModeEnum.Post");
                        }

                        if (value == null)
                        {
                            fileds.Add($"{columnName}=null");
                        }
                    }
                }
                else
                {
                    if (value == null || string.IsNullOrWhiteSpace(value.ToString()))
                    {
                        fileds.Add($"{columnName}=null");
                    }
                    else
                    {
                        fileds.Add($"{columnName}={value}");
                    }
                }
            }

            rows += string.Join(",", fileds);

            rows += $"}}";

            codes.Add(rows);
        }

        sb.Append(string.Join(",", codes));

        sb.Append(@");

    }
}
");

        AddData(entityName, codes);

        //验证文件是否存在
        if (!Directory.Exists(AppDomain.CurrentDomain.BaseDirectory + "codes"))
        {
            Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory + "/codes");
        }

        var fileName = "/codes/" + className + ".cs";

        if (File.Exists(AppDomain.CurrentDomain.BaseDirectory + fileName))
        {
            File.Delete(AppDomain.CurrentDomain.BaseDirectory + fileName);
        }

        File.WriteAllText(AppDomain.CurrentDomain.BaseDirectory + fileName, sb.ToString());
        Console.WriteLine("种子生成代码成功!!! fileName = " + fileName);
    }
    catch (Exception e)
    {
        Console.WriteLine(e.ToString());
    }
}

Console.WriteLine(useStringBuilder.ToString());
Console.WriteLine("完成!!!");

Console.ReadKey();

void AddData(string className, List<string> codes)
{
    StringBuilder sb = new();
    sb.AppendLine($"db.AddRange(new List<{className}>{{");
    var i = 1;
    foreach (var item in codes)
    {
        if (codes.Count == i)
        {
            sb.AppendLine($"{item}");
        }
        else
        {
            sb.AppendLine($"{item},");
        }

        i++;
    }

    sb.AppendLine("});");

    var str = $$"""
                public static class {{className}}AddData
                {
                    public static void AddData(DbContext db)
                    {
                        {{sb}}
                    }
                }
                """;

    //验证文件是否存在
    if (!Directory.Exists(AppDomain.CurrentDomain.BaseDirectory + "add_data"))
    {
        Directory.CreateDirectory(AppDomain.CurrentDomain.BaseDirectory + "/add_data");
    }

    var fileName = "/add_data/" + className + "AddData.cs";

    if (File.Exists(AppDomain.CurrentDomain.BaseDirectory + fileName))
    {
        File.Delete(AppDomain.CurrentDomain.BaseDirectory + fileName);
    }

    File.WriteAllText(AppDomain.CurrentDomain.BaseDirectory + fileName, str);
    Console.WriteLine("种子生成代码成功-add-data!!! fileName = " + fileName);
}